package cn.yuitstyle.license.starter.listener;

import cn.hutool.core.util.StrUtil;
import cn.yuitstyle.license.starter.bean.LicenseConfigBean;
import cn.yuitstyle.license.starter.model.LicenseVerifyParam;
import cn.yuitstyle.license.starter.util.LicenseVerify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author yuwg
 */
@Component
@Slf4j
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private LicenseConfigBean licenseConfigBean;
    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext().getParent();
        if (context==null){
            if (StrUtil.isNotBlank(licenseConfigBean.getLicensePath())){
                log.info("+++++++++开始安装证书+++++++++");
                LicenseVerifyParam licenseVerifyParam = new LicenseVerifyParam()
                        .setSubject(licenseConfigBean.getSubject())
                        .setPublicAlias(licenseConfigBean.getPublicAlias())
                        .setStorePass(licenseConfigBean.getStorePass())
                        .setLicensePath(licenseConfigBean.getLicensePath())
                        .setPublicKeysStorePath(licenseConfigBean.getPublicKeysStorePath());
                LicenseVerify licenseVerify = new LicenseVerify();
                licenseVerify.install(licenseVerifyParam, configurableApplicationContext);

                log.info("+++++++++证书安装完成+++++++++");
            }
        }
    }
}
